<template>
  <div class="repairman-home-container">
    <div class="repairman-home-header">
      <el-button @click="goBack" type="default" icon="ArrowLeft" class="back-button">返回</el-button>
      <div class="repairman-home-title">维修工工作台</div>
    </div>
    <div class="tabs-container">
      <el-tabs v-model="activeTab" type="border-card" @tab-change="handleTabChange" class="custom-tabs">
        <el-tab-pane label="处理中工单" name="processing">
          <div class="table-container">
            <el-table 
              :data="processingWorkorders"
              style="width: 100%"
              stripe
              border
              highlight-current-row
              :empty-text="emptyText">
              <el-table-column prop="orderId" label="工单编号" width="100"></el-table-column>
              <el-table-column prop="deviceCode" label="设备名称"></el-table-column>
              <el-table-column prop="description" label="故障描述"></el-table-column>
              <el-table-column prop="status" label="工单状态" width="120">
                <template #default="scope">
                  <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="提交时间" width="180"></el-table-column>
              <el-table-column label="操作" width="250" fixed="right">
                <template #default="scope">
                  <el-button size="small" type="success" @click="completeWorkorder(scope.row)" class="action-button success-button">完成维修</el-button>
                  <el-button size="small" type="danger" @click="scrapWorkorder(scope.row)" class="action-button danger-button">报废工单</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已完成工单" name="completed">
          <div class="table-container">
            <el-table 
              :data="completedWorkorders"
              style="width: 100%"
              stripe
              border
              highlight-current-row
              :empty-text="emptyText">
              <el-table-column prop="orderId" label="工单编号" width="100"></el-table-column>
              <el-table-column prop="deviceCode" label="设备名称"></el-table-column>
              <el-table-column prop="description" label="故障描述"></el-table-column>
              <el-table-column prop="rating" label="用户评分" width="100">
                <template #default="scope">
                  <el-rate v-model="scope.row.rating" :max="5" disabled></el-rate>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="提交时间" width="180"></el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import service from '~/axios';
import { toast } from '~/composables/util';
import { getToken} from '~/composables/auth';

const router = useRouter();
const activeTab = ref('processing');
const processingWorkorders = ref([]);
const completedWorkorders = ref([]);
const emptyText = ref('暂无工单数据');
const loading = ref(false);

onMounted(() => {
  if (!getToken()) {
    toast('请先登录', 'warning');
    router.push('/login');
    return;
  }

  fetchWorkorders(1); 
  setInterval(() => fetchWorkorders(getStatusByTab()), 300000);
});

const handleTabChange = () => {
  fetchWorkorders(getStatusByTab());
};

const getStatusByTab = () => {
  return activeTab.value === 'processing' ? 1 : 2;
};


const fetchWorkorders = async (status = 1) => {
const url = `/api/worker/order/${status}`; 
try {
  const res = await service.get(url);
  console.log(url);
  const responseData = res.data.data || [];
  console.log('接口返回的工单数据:', responseData);
  processingWorkorders.value = [];
  completedWorkorders.value = [];
  responseData.forEach(order => {
    if (order.status === 1) {
      processingWorkorders.value.push(order);
    } else if (order.status === 2) {
      completedWorkorders.value.push(order);
    }
  });

  if (processingWorkorders.value.length > 0) {
    checkNewWorkorders(processingWorkorders.value);
  }
  } catch (error) {
      toast('获取工单列表失败，请稍后重试', 'error');
  }
};

const checkNewWorkorders = (newWorkorders) => {
  console.log('有新的维修工单，请及时处理:', newWorkorders);
};

const getStatusText = (status) => {
  const statusMap = {
    1: '处理中',
    2: '已完成'
  };
  return statusMap[status] || '未知状态';
};

const getStatusTagType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success'
  };
  return typeMap[status] || 'default';
};

const completeWorkorder = async (row) => {
  try {
    await service.post('/api/worker/order', { 
      orderId: row.orderId, 
      status: 2 
    });
    toast('已标记工单为成功');
    fetchWorkorders();
  } catch (error) {
    toast('标记工单成功失败，请稍后重试', 'error');
  }
};

const scrapWorkorder = async (row) => {
  try {
    await service.post('/api/worker/order', { 
      orderId: row.orderId, 
      status: 3 
    });
    toast('已标记工单为报废');
    fetchWorkorders();
  } catch (error) {
    toast('标记工单报废失败，请稍后重试', 'error');
  }
};

const commentWorkorder = (row) => {
  router.push({ path: '/repairman-comment', query: { id: row.id } });
};

const goBack = () => {
  router.back();
};
</script>

<style scoped>
.repairman-home-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.repairman-home-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}

.back-button {
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateX(-2px);
}

.repairman-home-title {
  font-size: 28px;
  font-weight: 600;
  color: #297062;
  margin: 0;
}

.tabs-container {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: all 0.3s ease;
}

.tabs-container:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
}

.custom-tabs {
  border: none;
}

.table-container {
  margin-top: 16px;
  overflow-x: auto;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header th {
  background-color: #f7f9fa;
  font-weight: 600;
  color: #333;
}

.el-table__body tr:hover {
  background-color: #f5f7fa;
}

.action-button {
  margin-right: 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.success-button {
  background-color: #52c41a;
  border-color: #52c41a;
}

.danger-button {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
}

.el-rate {
  color: #faad14;
}

@media (max-width: 768px) {
  .repairman-home-container {
    padding: 10px;
  }

  .repairman-home-title {
    font-size: 22px;
  }

  .tabs-container {
    padding: 10px;
  }
}

.el-empty__description {
  color: #909399;
}

.el-empty {
  padding: 40px 0;
}
</style>
